package net.anzhuo.controller.db;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.Date;
import java.util.List;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import net.anzhuo.common.utils.CompanyNameUtils;
import net.anzhuo.common.utils.DateUtil;

import net.anzhuo.entity.GsBase;
import net.anzhuo.entity.GsBranch;

import net.anzhuo.entity.GsGudong;
import net.anzhuo.entity.GsOuttouzi;
import net.anzhuo.entity.GsPersonRelationship;
import net.anzhuo.entity.GsQuery;
import net.anzhuo.entity.db.spiderman.DetailList;
import net.anzhuo.entity.db.spiderman.Gudong;
import net.anzhuo.entity.db.spiderman.JsonRootBean;
import net.anzhuo.entity.db.spiderman.Kg;
import net.anzhuo.entity.db.spiderman.Kzr;
import net.anzhuo.entity.db.spiderman.SyrNames;
import net.anzhuo.entity.db.spiderman.Oper;
import net.anzhuo.entity.db.spiderman.Syr;
import net.anzhuo.entity.db.spiderman.Touzi;
import net.anzhuo.entity.db.syncdata.PairValue;
import net.anzhuo.entity.db.syncdata.QueryKeyNoResult;
import net.anzhuo.entity.db.syncdata.UpdateKeyNoResult;
import net.anzhuo.entity.equitypenetration.EnquityPenetrationResult;
import net.anzhuo.entity.equitypenetration.EnquityResult;
import net.anzhuo.entity.equitypenetration.KeyNoListResult;
import net.anzhuo.entity.personcompanyrelation.PersonCompanyRelation;
import net.anzhuo.service.GsBaseService;
import net.anzhuo.service.GsBranchService;
import net.anzhuo.service.GsGudongService;
import net.anzhuo.service.GsOuttouziService;
import net.anzhuo.service.GsPersonRelationshipService;
import net.anzhuo.service.GsQueryService;

@RestController
@Slf4j
public class PersonRelationshipController {

	@Autowired
	private TransportClient client;

	@Autowired
	private GsPersonRelationshipService gsPersonRelationshipService;

	@Autowired
	private GsBaseService gsBaseService;

	@Autowired
	private GsBranchService gsBranchService;

	@Autowired
	private GsGudongService gsGudongService;

	@Autowired
	private GsOuttouziService gsOutouziService;
	
	
	@Autowired
	private GsQueryService gsQueryService;

	public List<DetailList> getDetailListRep(List<DetailList> list, Gudong gudong) {

		for (int i = 0; i < list.size(); i++) {
			DetailList g = list.get(i);
			if (g.DetailCount > 0) {
				g.DetailList = this.getDetailListRep(g.DetailList, gudong);
			}

			if (g.KeyNo.substring(0, 1).equals("p")) {
				List<GsBase> gsBaselist = gsBaseService.getByNameList(gudong.Name);
				GsBase gsBase = new GsBase();
				for (int x = 0; x < gsBaselist.size(); x++) {
					if (x == 0) {
						gsBase = gsBaselist.get(x);
					} else {
						gsBaseService.delete(gsBaselist.get(x).getId());
					}
				}
				if (gsBase != null) {
					List<GsGudong> listGudong = gsGudongService.getByMd5(gsBase.getMd5());
					for (GsGudong g1 : listGudong) {
						if (g1.getShareholder() != null) {
							if (g1.getShareholder().trim().equals(g.Name)) {
								g1.setMd5(g.KeyNo);
								if (g1.getCapitaltype().equals("自然人股东")) {
									g1.setCapitaltype("1");
								} else if (g1.getCapitaltype().equals("企业法人")) {
									g1.setCapitaltype("2");
								} else if (g1.getCapitaltype().equals("法人股东")) {
									g1.setCapitaltype("3");
								} else if (g1.getCapitaltype().equals("事业法人")) {
									g1.setCapitaltype("4");
								}
								gsGudongService.update(g1);
							}
						}
					}
				}
			} else {
				List<GsBase> gsBaselist = gsBaseService.getByNameList(gudong.Name);
				GsBase gsBase = new GsBase();
				for (int x = 0; x < gsBaselist.size(); x++) {
					if (x == 0) {
						gsBase = gsBaselist.get(x);
					} else {
						gsBaseService.delete(gsBaselist.get(x).getId());
					}
				}
				if (gsBase != null) {
					List<GsBranch> listBranch = gsBranchService.getByMd5(gudong.Name);
					for (GsBranch g2 : listBranch) {
						if (g2.getEnterpriseName() != null) {
							if (g.Name.equals(g2.getEnterpriseName().trim())) {
								g.KeyNo = g2.getMd5();
							}
						}
					}
				}
			}
			list.set(i, g);
		}
		return list;
	}

	public List<DetailList> getDetailListTouZiRep(List<DetailList> list, Touzi touzi) {

		for (int i = 0; i < list.size(); i++) {
			DetailList g = list.get(i);
			if (g.DetailCount > 0) {
				g.DetailList = this.getDetailListTouZiRep(g.DetailList, touzi);
			}
			List<GsBase> gsBaselist = gsBaseService.getByNameList(touzi.Name);
			GsBase gsBase = new GsBase();
			for (int x = 0; x < gsBaselist.size(); x++) {
				if (x == 0) {
					gsBase = gsBaselist.get(x);
				} else {
					gsBaseService.delete(gsBaselist.get(x).getId());
				}
			}

			if (gsBase != null) {
				GsOuttouzi go = new GsOuttouzi();
				go.setCoMd5(gsBase.getMd5());
				go.setEnterpriseName(g.Name);
				List<GsOuttouzi> listOut = gsOutouziService.getListByName(go);
				for (GsOuttouzi g1 : listOut) {
					g.KeyNo = g1.getMd5();
				}
			}

			list.set(i, g);
		}
		return list;
	}

	

	public List<SyrNames> getSYRNames(List<SyrNames> list, Syr syr) {
		ArrayList<SyrNames> lista = new ArrayList<SyrNames>();
		for (SyrNames g : list) {

			GsGudong gss = new GsGudong();
			gss.setShareholder(g.Name);
			gss.setCoMd5(syr.KeyNo);
			List<GsGudong> listOper = gsGudongService.getByName(gss);
			if (listOper.size() > 0) {
				GsGudong gsGudong = listOper.get(0);
				gsGudong.setMd5(g.KeyNo);
			}
			lista.add(g);
		}

		return lista;
	}

	@RequestMapping("/PersonRelationshipKeyNoList")
	public QueryKeyNoResult PersonRelationshipKeyNoList(String status) {
		log.info("===>PersonRelationshipKeyNoList=" + status);
		long startTime = System.currentTimeMillis();
		QueryKeyNoResult qknr = new QueryKeyNoResult();
		try {

			qknr.setStatus("200");
			qknr.setMessage("查询成功");
			GsPersonRelationship gp = new GsPersonRelationship();
			gp.setStatus(status);
			List<GsPersonRelationship> list = gsPersonRelationshipService.getList(gp);

			List<PairValue> keyNoList = new ArrayList<PairValue>();
			PairValue pv = new PairValue();
			for (GsPersonRelationship g : list) {

				pv = new PairValue();
				pv.setKeyNo(g.getKeyNo());
				if (gsBaseService.getByMd5(g.getKeyNo()) != null) {
					if (gsBaseService.getByMd5(g.getKeyNo()).getName() != null
							&& !gsBaseService.getByMd5(g.getKeyNo()).getName().equals("")) {
						pv.setName(gsBaseService.getByMd5(g.getKeyNo()).getName());
						pv.setCreditCode(gsBaseService.getByMd5(g.getKeyNo()).getCreditCode());
						log.info("Name not null=" + g.getKeyNo() + ":" + pv.getName());
					} else {
						if (gsBaseService.getByMd5(g.getKeyNo()).getCreditCode() != null
								&& !gsBaseService.getByMd5(g.getKeyNo()).getCreditCode().equals("")) {
							// pv.setName(gsBaseService.getByMd5(g.getKeyNo()).getCreditCode());
							// log.info("Name is null and credit is not null="+pv.getName());
						} else {
							continue;
						}
					}
				}
				keyNoList.add(pv);
			}
			qknr.setCount(keyNoList.size());
			log.info("size=" + keyNoList.size());
			qknr.setKeyNoList(keyNoList);
		} catch (Exception e1) {
			log.info(e1.getMessage());
		}
		long endTime = System.currentTimeMillis();
		float excTime = (float) (endTime - startTime) / 1000;
		log.info(" PersonRelationshipKeyNoList 执行时间：" + excTime + "s");
		return qknr;
	}

	@RequestMapping("/UpdatePersonRelationshipKeyNo")
	public UpdateKeyNoResult UpdatePersonRelationshipKeyNo(String keyNo, String data, String status) {
		log.info("===>UpdatePersonRelationshipKeyNo=" + keyNo);
		long startTime = System.currentTimeMillis();
		UpdateKeyNoResult qknr = new UpdateKeyNoResult();

		try {

			qknr.setStatus("200");
			qknr.setMessage("查询成功");
			GsPersonRelationship gp = new GsPersonRelationship();
			gp.setKeyNo(keyNo);
			gp.setStatus(status);
			gp.setData(data);
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String str = sdf.format(date);

			gp.setUpdateTime(str);
			gsPersonRelationshipService.update(gp);

		} catch (Exception e1) {
			log.info(e1.getMessage());
		}

		long endTime = System.currentTimeMillis();
		float excTime = (float) (endTime - startTime) / 1000;
		log.info(" UpdatePersonRelationshipKeyNo 执行时间：" + excTime + "s");
		return qknr;
	}

	@RequestMapping("/PersonCompanyRelationshipLocal")
	public EnquityPenetrationResult PersonCompanyRelationship(String keyword) {
		log.info("===>PersonCompanyRelationship=" + keyword);
		EnquityPenetrationResult ep = new EnquityPenetrationResult();
		QueryBuilder query = QueryBuilders.boolQuery()
				.must(QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery("md5", keyword)));
		ArrayList<KeyNoListResult> list = new ArrayList<KeyNoListResult>();
		KeyNoListResult knr = new KeyNoListResult();
        if(keyword==null|| keyword.equals(""))
        {
        	return ep;
        }
		GsPersonRelationship gs = new GsPersonRelationship();
		gs.setKeyNo(keyword);
		gs.setStatus("0");
		gs.setUpdateTime(DateUtil.getDate("yyyy-MM-dd"));
		List<GsPersonRelationship> li = gsPersonRelationshipService.getBycoMd5(knr.getKeyNo());
		if (li.size() == 0) {
			gsPersonRelationshipService.save(gs);
		} else {
			if (li.get(0).getData().length() > 200) {
				gs.setStatus("1");
				gs.setId(li.get(0).getId());
				gsPersonRelationshipService.update(gs);
			} else {
				gs.setId(li.get(0).getId());
				gsPersonRelationshipService.update(gs);
			}
		}

		List<GsPersonRelationship> listResult = gsPersonRelationshipService.getBycoMd5(keyword);
		GsPersonRelationship gp = new GsPersonRelationship();
		if (listResult.size() > 0) {

			gp = listResult.get(0);
			while (gp.getStatus().equals("0")) {
				listResult = gsPersonRelationshipService.getBycoMd5(keyword);
				if (listResult.size() > 0) {
					gp = listResult.get(0);

				}
			}
		}
		String data = gp.getData();

		ep.setData(data);
		long startTime = System.currentTimeMillis();
		long endTime = System.currentTimeMillis();
		float excTime = (float) (endTime - startTime) / 1000;
		log.info(" PersonCompanyRelationship 执行时间：" + excTime + "s");
		return ep;
	}

	@RequestMapping("/PersonCompanyRelationship")
	public EnquityPenetrationResult PersonCompanyRelationshipLocal(String keyword) {
		log.info("===>PersonCompanyRelationshipLocal=" + keyword);
		EnquityPenetrationResult ep = new EnquityPenetrationResult();
		QueryBuilder query = QueryBuilders.boolQuery()
				.must(QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery("md5", keyword)));
		ArrayList<KeyNoListResult> list = new ArrayList<KeyNoListResult>();
		KeyNoListResult knr = new KeyNoListResult();
		 if(keyword==null|| keyword.equals(""))
	        {
	        	return ep;
	        }
		 knr.setKeyNo(keyword);
		GsPersonRelationship gs = new GsPersonRelationship();
		gs.setKeyNo(keyword);
		gs.setLegal(knr.getLegal());
		gs.setName(knr.getName());
		gs.setStatus("0");
		gs.setUpdateTime(DateUtil.getDate("yyyy-MM-dd"));
		
		List<GsPersonRelationship> li = gsPersonRelationshipService.getBycoMd5(knr.getKeyNo());
		if (li.size() == 0) {
			gsPersonRelationshipService.save(gs);
		} else {
			gs.setId(li.get(0).getId());
			if (li.get(0).getData().length() > 200) {
				gs.setStatus("1");
				gsPersonRelationshipService.update(gs);
			} else {
				gsPersonRelationshipService.update(gs);
			}
		}
		List<GsPersonRelationship> listResult = gsPersonRelationshipService.getBycoMd5(keyword);
		GsPersonRelationship gp = new GsPersonRelationship();
		if (listResult.size() > 0) {
			gp = listResult.get(0);
			while (gp.getStatus().equals("0")) {
				listResult = gsPersonRelationshipService.getBycoMd5(keyword);
				if (listResult.size() > 0) {
					gp = listResult.get(0);

				}
			}
		}
		// keyNo replace
		String data = gp.getData();
		PersonCompanyRelation ep1 = JSON.parseObject(data, PersonCompanyRelation.class);
		net.anzhuo.entity.personcompanyrelation.Success success=ep1.getSuccess();
		List<net.anzhuo.entity.personcompanyrelation.Results> resultList=success.getResults();
		for(int i=0;i<resultList.size();i++)
		{
			net.anzhuo.entity.personcompanyrelation.Results result=resultList.get(i);
			List<net.anzhuo.entity.personcompanyrelation.Data> dataList=result.data;
			for(int j=0;j<dataList.size();j++)
			{
				net.anzhuo.entity.personcompanyrelation.Data dataa=dataList.get(j);
				net.anzhuo.entity.personcompanyrelation.Graph graph=dataa.graph;
				List<net.anzhuo.entity.personcompanyrelation.Nodes> nodes=graph.nodes;
				for(int z=0;z<nodes.size();z++)
				{
					net.anzhuo.entity.personcompanyrelation.Nodes node=nodes.get(z);
					if(node.labels.size()==1)
					{
						String flag=node.labels.get(0);
						if(flag.equals("Company"))
						{
							List<GsBase> listGsBase=gsBaseService.getByNameList(CompanyNameUtils.getEnglishBraces(node.properties.name));
							List<GsBase> listGsBaseSec=gsBaseService.getByNameList(CompanyNameUtils.getChineseBraces(node.properties.name));
							if(listGsBase.size()==0&&listGsBaseSec.size()==0)
							{
								GsQuery gsQuery=new GsQuery();
								gsQuery.setName(node.properties.name);
								gsQuery.setKeyNo(node.properties.keyNo);
								gsQuery.setUpdateTime(DateUtil.getDate("yyyy-MM-dd"));
								List<GsQuery> listQuery=gsQueryService.getList(gsQuery);
								if(listQuery.size()==0)
								{
									gsQuery.setStatus("0");
									gsQueryService.save(gsQuery);
								}
							}else
							{
								GsBase gsBase=new GsBase();
								if(listGsBase.size()>0)
								{
									gsBase=listGsBase.get(0);
								}else 
								{
									gsBase=listGsBaseSec.get(0);
								}
								node.properties.keyNo=gsBase.getMd5();
							}
						}
					}
					
					nodes.set(z, node);
				}
				graph.setNodes(nodes);
				dataa.setGraph(graph);
				dataList.set(j, dataa);
			}			
			resultList.set(i,result);
		}
		success.setResults(resultList);
		ep1.setSuccess(success);
		String dataLocal = JSON.toJSONString(ep1);
		ep.setData(dataLocal);
		long startTime = System.currentTimeMillis();
		long endTime = System.currentTimeMillis();
		float excTime = (float) (endTime - startTime) / 1000;
		log.info(" PersonCompanyRelationshipLocal 执行时间：" + excTime + "s");
		return ep;
	}

	// result
	@RequestMapping("/PersonRelationshipSearchResult")
	public EnquityResult PersonRelationshipSearchResult(String keyword) {
		log.info("===>PersonRelationshipSearchResult=" + keyword);
		EnquityResult ep = new EnquityResult();
		SearchResponse response = null;
		if (keyword.length() > 4) {
			QueryBuilder query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery("name", keyword)));

			response = client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC)
					.addSort("_score", SortOrder.DESC).setFrom((Integer.parseInt("1") - 1) * 200).setSize(200).execute()
					.actionGet();
		} else {
			QueryBuilder query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery("legal", keyword)));
			response = client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC)
					.addSort("_score", SortOrder.DESC).setFrom((Integer.parseInt("1") - 1) * 200).setSize(200).execute()
					.actionGet();

		}
		List<net.anzhuo.entity.equitypenetration.Result> list = new ArrayList<net.anzhuo.entity.equitypenetration.Result>();
		if (response.getHits().getTotalHits() > 0) {
			{
				for (SearchHit searchHit : response.getHits()) {
					net.anzhuo.entity.equitypenetration.Result r = new net.anzhuo.entity.equitypenetration.Result();
					r.setKeyNo((String) searchHit.getSource().get("md5"));
					r.setName((String) searchHit.getSource().get("name"));
					r.setLegal((String) searchHit.getSource().get("legal"));
					r.setProvince(((String) searchHit.getSource().get("province")));
					GsPersonRelationship gs = new GsPersonRelationship();
					gs.setKeyNo(r.getKeyNo());
					gs.setLegal(r.getLegal());
					gs.setName(r.getName());
					gs.setStatus("0");
					gs.setUpdateTime(DateUtil.getDate("yyyy-MM-dd"));
					List<GsPersonRelationship> li = gsPersonRelationshipService.getBycoMd5(r.getKeyNo());
					if (li.size() == 0) {
						gsPersonRelationshipService.save(gs);
					} else {
						gsPersonRelationshipService.update(gs);
					}
					list.add(r);
				}
			}
		}
		ep.setResult(list);
		long startTime = System.currentTimeMillis();
		long endTime = System.currentTimeMillis();
		float excTime = (float) (endTime - startTime) / 1000;
		log.info(" PersonRelationshipSearchResult 执行时间：" + excTime + "s");
		return ep;
	}
}
